/**
 * Created by Administrator on 2017/7/10.
 */
"use strict";
const helpConst = require('./helpConst');
const async = require("async");

module.exports = {
    handler(req, res, next) {
        req.mongo.collection("api").aggregate([
            {$sort: {app: 1, route: 1}},
            {
                $group: {
                    _id: {app: "$app", route: "$route"},
                    items: {$addToSet: {_id: "$_id"}}
                }
            }
        ], (err, r)=> {
            if (err) {
                return  res.reply({message:err});
            }

            let helpArray=[];
             r.forEach((x)=> {
                    let item={};
                    item._id = x._id.route;
                    if (helpConst.routeName[x._id.route]){
                        item.name = helpConst.routeName[item._id];
                    }
                    item.items=[];


                    x.items.forEach((m,j)=>{
                        let api = {_id:m._id,name:''};
                        if (helpConst.apiName[m._id]){
                            api.name = helpConst.apiName[m._id];
                        }
                        item.items.push(api);
                    });
                    helpArray.push(item);
                    r.hasNext().then((data)=>{
                        if(!data){
                            console.log('################',data);
                           res.reply(helpArray);
                        }
                    });
                })
        });
    }
};